import toggleTableOperation from "@/mixins/toggleTableOperation";
import recursion from "@/util/recursion";

export default {
    mixins: [toggleTableOperation],
    data() {
        return {
            userName: localStorage.getItem("ziyunFactoryPortalName"),
            dpList: [],
            projectTypeList: [
                {
                    value: 1,
                    label: this.$t('全球项目')
                }, {
                    value: 2,
                    label: this.$t('本地项目')
                }
            ],
            statusList: [
                {
                    value: "0",
                    label: this.$t('进行中')
                },
                {
                    value: "1",
                    label: this.$t('已结束')
                }
            ],
            approvalList: [
                {
                    value: 1,
                    label: this.$t('通过1')
                },
                {
                    value: 0,
                    label: this.$t('驳回')
                }
            ],
            processList: [
                {
                    icon: "zy-common-a-Specin",
                    name: this.$t('需求起草'),
                    key: ["Spec. In"],
                    cKey: "specIn"
                },
                {
                    icon: "zy-common-Bidding",
                    name: this.$t('投标'),
                    key: ["Bidding"],
                    cKey: "bidding"
                },
                {
                    icon: "zy-common-a-ConfirmVendorr",
                    name: this.$t('确定供应商'),
                    key: ["Confirm Vendor", "Confirm Vendor Approval"],
                    cKey: "confirmVendor"
                },
                // {
                //     icon: "zy-common-a-BDGApproval",
                //     name: this.$t('预算审批'),
                //     key: ["BDG Approval"]
                // },
                {
                    icon: "zy-common-Soec-Out",
                    name: this.$t('需求定稿'),
                    key: ["Spec. Out"],
                    cKey: "specOut"

                },
                {
                    icon: "zy-common-a-ContractSign-off",
                    name: this.$t('签署合同'),
                    key: ["Contract Sign-off"],
                    cKey: "contractSignOff"
                },
                {
                    icon: "zy-common-PR",
                    name: this.$t('采购申请'),
                    key: ["PR"],
                    cKey: "pr"
                },
                {
                    icon: "zy-common-a-DownPayment",
                    name: this.$t('支付首期款'),
                    key: ["Down Payment", "Down Payment Approval"],
                    cKey: "downPayment"
                },
                {
                    icon: "zy-common-STA",
                    name: this.$t('供应商处预验收'),
                    key: ["SAT", "SAT Approval"],
                    cKey: "sat"
                },
                {
                    icon: "zy-common-CAT",
                    name: this.$t('交付验收'),
                    key: ["CAT", "CAT Approval"],
                    cKey: "cat"
                },
                {
                    icon: "zy-common-a-DownPayment",
                    name: this.$t('第二次付款'),
                    key: ["2nd Payment", "2nd Payment Approval"],
                    cKey: "downPayment2"
                },
                {
                    icon: "zy-common-FAT",
                    name: this.$t('最终验收'),
                    key: ["FAT", "FAT Approval"],
                    cKey: "fat"
                },
                {
                    icon: "zy-common-a-DownPayment",
                    name: this.$t('第三次付款'),
                    key: ["3nd Payment", "3nd Payment Approval"],
                    cKey: "downPayment3"
                },
                {
                    icon: "zy-common-Capitalization",
                    name: this.$t('转固'),
                    key: ["Capitalization", "Capitalization Approval"],
                    cKey: "capitalization"
                },
                {
                    icon: "zy-common-a-PostCalculation",
                    name: this.$t('财务核算'),
                    key: ["Post Calculation"],
                    cKey: "postCalculation"
                }
            ],
            orgList: [],
            businessPurposeList: [
                {label: "Manufacturing Process Deveopment"},
                {label: "New Product/Component implementation"},
                {label: "Capacity Expansion"},
                {label: "Facilities"},
                {label: "Cost Reduction"},
                {label: "Safety / Quality"},
                {label: "Information Technology"},
                {label: "Others"}
            ],
            acquisitionMethodList: [
                {label: "Build"},
                {label: "New Purchase"},
                {label: "Fixed Assets Improvement"},
                {label: "Direct Replacement"},
            ],
            capitalCategoriesList: [
                {label: "Machines and Equipment_NPCI"},
                {label: "Machines and Equipment_Productivity"},
                {label: "Machines and Equipment_Sourcing"},
                {label: "Land & Building"},
                {label: "Computer Hardware (IT Infrastructure)"},
                {label: "Software"},
                {label: "Facility (including furniture)"},
                {label: "Other Equipment（include Tooling)"},
                {label: "Other Intangible Assets"},
            ],
            paymentList: [
                {label: "Check draft"},
                {label: "Cash check"},
                {label: "Remittance"},
                {label: "Petty cash"},
            ],
            catResultList: [
                {label: "CAT-accepted"},
                {label: "Conditionally CAT"},
            ],
            fatResultList: [
                {label: "The machine or equipment is accepted by KONE"},
                {label: "The machine or equipment is conditionally accepted by KONE"},
            ],
            satResultList: [
                {label: "SAT-accepted"},
                {label: "Conditionally SAT"},
            ],
            resultList: [
                {label: "OK"},
                {label: "NG"},
                {label: "N/A"},
            ],
            herewithAcceptedDetailList: [
                {label: "有一些小问题，供货商必须整改或更换零部件，在右述日期前："},
                {label: "KONE认为不需要再作进一步验收或检查。"},
                {label: "全部技术方面的细节和结果可参见验收报告。日期为："},
            ],
            capCagegory: [
                {label: "Land & Building"},
                {label: "Machines and Equipment"},
                {label: "Computer Hardware (IT Infrastructure)"},
                {label: "Computer Software"},
                {label: "Other Software"},
                {label: "Other Equipment（include Tooling)"},
                {label: "Other Intangible Assets"},
            ],
            capAcquisitionMethod: [
                {label: "Self-built"},
                {label: "Purchased"},
                {label: "Other"}
            ],
            capAppendix: [
                {label: "CAPEX Application"},
                {label: "Purchase Order"},
                {label: "Purchase Contract"},
                {label: "Final Settlement Report"},
                {label: "Certificate of qualification"},
                {label: "Others"}
            ],
            capConcluison: [
                {label: "Accepted, Meet requirements"},
                {label: "Not meet requirements, need retrofit"},
                {label: "Not meet requirements,need to return"}
            ],
            processScheduleData: "",
            budgetList: [
                {label: this.$t('上年结转'), value: "1"},
                {label: this.$t('当年预算'), value: "2"},
                {label: this.$t('没有预算'), value: "3"},
            ],
            companyList: [
                {label: this.$t('昆山'), value: 1},
                {label: this.$t('其他'), value: 2}
            ]
        }
    },
    methods: {
        validateInput(rule, value, callback) {
            if (!value) {
                callback(new Error(this.$t('请输入')));
            } else {
                callback();
            }
        },
        validateSelect(rule, value, callback) {
            if (!value) {
                callback(new Error(this.$t('请选择')));
            } else {
                callback();
            }
        },
        validateUpload(rule, value, callback) {
            if (!value) {
                callback(new Error(this.$t('请上传')));
            } else {
                callback();
            }
        },
        formatProcessList(active, flows, isEnd, satIsRequired = 1, twoPaymentBeforeCat = 0) {
            let codeStatus = true
            let list = JSON.parse(JSON.stringify(this.processList))

            /**
             * 处理跳过以及置换位置数据
             * @type {*[]}
             */
            let arr = []
            // if (biddingIsRequired != 1) arr.push("Bidding")
            if (satIsRequired != 1) arr.push("SAT", "SAT Approval")
            let payment2Index = 0
            let payment2 = {}
            if (arr.length > 0 || twoPaymentBeforeCat == 1)
                list = list.filter((item, index) => {
                    let status = false;
                    arr.forEach((code) => {
                        status = item.key.includes(code)
                    })

                    if (twoPaymentBeforeCat == 1) {
                        if (item.key.includes('CAT')) {
                            payment2Index = index
                        }
                        if (item.key.includes('2nd Payment')) {
                            payment2 = item;
                            status = true
                        }
                    }

                    if (!status)
                        return item;
                })

            // if (satIsRequired==1) payment2Index = payment2Index - 1

            if (payment2Index > 0) {
                for (let i = 0; i < list.length; i++) {
                    if (list[i].key.includes('CAT')) {
                        payment2Index = i
                        break;
                    }
                }
            }


            if (twoPaymentBeforeCat == 1 && payment2Index > 0) {
                list.splice(payment2Index, 0, payment2)
            }

            /**
             * 节点绑定审批，提交数据
             * @type {*[]}
             */
            list.forEach((item, index) => {
                if (Array.isArray(flows)) {
                    const obj = flows.filter(m => item.key.includes(m.progressCode))
                    if (Array.isArray(obj)) {
                        for (let i = 0; i < obj.length; i++) {
                            if (obj[i].approvalTime)
                                item.approvalTime = obj[i].approvalTime
                            if (obj[i].submitTime)
                                item.submitTime = obj[i].submitTime
                            // if (item.key.includes('BDG Approval')) {
                                // item.submitTime = obj[i].approvalTime
                            // }
                        }
                    }
                }
                if (codeStatus) {
                    item.status = 1
                }

                if (!isEnd) {
                    if (item.key.includes(active)) {
                        item.status = 2;
                        codeStatus = false
                        if (index - 1 >= 0) {
                            list[index - 1].isTop = true
                        }
                        if (index !== list.length - 1) {
                            list[index + 1].isBottom = true
                        }

                        if (index === 0) {
                            list[index].isCurrentTop = true
                        }
                        if (index === list.length - 1) {
                            list[index].isCurrentBottom = true
                        }
                    } else {
                        if (!codeStatus) {
                            item.status = 3
                        }
                    }
                } else {
                    item.status = 1;
                }
            })

            return list
        },
        getDeptList() {
            return new Promise(resolve => {
                if (Array.isArray(this.orgList) && this.orgList.length > 0)
                    resolve(this.orgList)
                else
                    this.axios({
                        method: 'get',
                        url: '/dms/capex/findListByTokenAndDict',
                        params: {level: 3}
                    }).then(res => {
                        if (res.code === 200) {
                            const obj = {label: 'name', value: 'id', children: 'children'}
                            this.orgList = recursion.convertTree(res.data, obj)
                            resolve(this.orgList)
                        } else {
                            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                        }
                    })
            })
        },
        getdpList() {
            return new Promise(resolve => {
                if (Array.isArray(this.dpList) && this.dpList.length > 0)
                    resolve(this.dpList)
                else
                    this.axios({
                        method: 'post',
                        url: '/basic/dept/list',
                        data: {pageNo: 1, pageSize: 1000}
                    }).then(res => {
                        if (res.code === 200) {
                            const obj = {label: 'deptName', value: 'id', children: 'children'}
                            this.dpList = recursion.convertTree(res.data.list, obj)
                            resolve(this.dpList)
                        } else {
                            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                        }
                    })
            })
        },
        getDTApprovalRole(list = []) {
            if (!(Array.isArray(list) && list.length > 0)) list = []
            const obj = list.find(item => item.status === 0)
            return obj || {}
        },
        // getRejectDTApprovalRole(status, list) {
        //     if (status == 1) {
        //         const obj = this.getDTApprovalRole(list)
        //         return obj.progressCode
        //     } else {
        //         const obj = {}
        //         list.forEach(item => {
        //             if (item.status == 1) obj = item;
        //         })
        //         debugger
        //         if (!obj && !obj.progressCode) {
        //             obj = list[0]
        //         }
        //         return obj.progressCode
        //     }
        // },
        printModalShow(type, info) {

            this.$emit('print', {type, info})
        },
        printPreviewPdf(type, info) {
            const isTong = process.env.NODE_ENV === 'tong';
            let ksiot = '';
            if (isTong) {
                ksiot = ''
            }

            const sourceObj = {
                'CAT': '/catPrint?id=' + info.id,
                'SAT': '/satPrint?id=' + info.id,
                'FAT': '/fatPrint?id=' + info.id,
                'SOC': '/capital?id=' + info.id,
                'PAY1': '/downPayment?type=1&id=' + info.id,
                'PAY2': '/downPayment?type=2&id=' + info.id,
                'PAY3': '/downPayment?type=3&id=' + info.id,
                'CAP': '/fixedAssetPrint?id=' + info.id
            }
            this.$store.commit('capex', {...this.$store.state.capex, [type + info.id]: info})
            window.open(ksiot + sourceObj[type], '_blank')
        },
        getProcessLayoutList(components, info) {
            const {satIsRequired, twoPaymentBeforeCat} = info;
            const arr = []
            let downPayment2 = []
            let downPayment2Index = 0
            // if (biddingIsRequired != 1) arr.push('Bidding')
            if (satIsRequired != 1) arr.push('SAT', 'SAT Approval')

            let _components = components.filter((item, index) => {
                if (twoPaymentBeforeCat == 1) {
                    if (item.processCode === 'downPayment2') {
                        downPayment2.push(item)
                    }
                    if (item.key === 'CAT') {
                        downPayment2Index = index
                    }
                }
                if (!(arr.length > 0 && arr.includes(item.key))) {
                    if (!(item.processCode === 'downPayment2' && twoPaymentBeforeCat == 1))
                        return item;
                }
            })


            if (downPayment2Index > 0) {
                for (let i = 0; i < _components.length; i++) {
                    if (_components[i].key.includes('CAT')) {
                        downPayment2Index = i
                        break;
                    }
                }
            }


            if (twoPaymentBeforeCat == 1) {
                _components.splice(downPayment2Index, 0, downPayment2[0])
                _components.splice(downPayment2Index + 1, 0, downPayment2[1])
            }


            let list = [];


            for (let i = 0; i < _components.length; i++) {
                list.push({..._components[i], disabled: true})
                if (_components[i]['key'] === info.progressCode) {
                    if (i < _components.length - 1) {

                        list.push({..._components[i + 1], disabled: false})
                    }
                    break;
                }
            }

            return list
        },
        getCurrentApproval(list, code) {
            if (!(Array.isArray(list) && list.length > 0)) return {}
            return list.find(item => item.progressCode == code) || {}
        },
        getCurrentReject(list, code) {
            if (!(Array.isArray(list) && list.length > 0)) return {}
            return list.find(item => item.progressCode == code + ' Approval') || {}
        },
        calculatingBackRate(bdgAmount, list) {
            let total = 0;
            let fYear = -1;
            let fAmout = 0;
            let overYear = {estimatedBenefits: 0}
            const len = list.length

            for (let i = 0; i < len; i++) {
                total = total + list[i].estimatedBenefits / 1;
                fYear++
                if (total >= bdgAmount) {
                    overYear = list[i];
                    if (total === bdgAmount)
                    {
                        fAmout = total
                       if (fYear < 1) fYear = 1
                    }
                    break;
                } else {
                    fAmout = total / 1
                }
            }
            if (total < bdgAmount) {
                return 0
            }

            const value = len > 0 ? fYear + ((bdgAmount - fAmout) / (overYear.estimatedBenefits / 1 / 12) / 12) : 0
            return value.toFixed(2)
        },
        getCacheData(data) {
            let {cacheInfo, flows} = data;
            if (!cacheInfo) return {}
            cacheInfo = JSON.parse(cacheInfo)
            const {progressCode} = cacheInfo

            let params = {};

            if (!Array.isArray(flows)) flows = []


            flows.push({
                submitRemark: cacheInfo.remark,
                progressCode
            })


            switch (progressCode) {
                case 'Bidding':
                    params = {
                        ...cacheInfo
                    }
                    break;
                case "Confirm Vendor":
                    params = {
                        ...cacheInfo,
                        cvInfo: {
                            ...cacheInfo.cvInfo,
                            id: 1
                        },
                        prNo: cacheInfo.cvInfo.prNo

                    }
                    break;
                case "Spec. Out":
                    params = {
                        ...cacheInfo
                    }
                    break;
                case "Contract Sign-off":
                    params = {
                        ...cacheInfo
                    }
                    break;
                case "PR":
                    params = {
                        ...cacheInfo
                    }
                    break;
                case "Down Payment":
                    params = {
                        downPaymentDto1: {...cacheInfo.downPaymentDto, id: 1},
                        downPaymentDetailDtos: cacheInfo.downPaymentDetailDtos,
                        dpSubmitProgressCode: cacheInfo.dpSubmitProgressCode
                    }
                    break;
                case "SAT":
                    params = {
                        satDetailDtos: cacheInfo.scfDetailDtos,
                        satInfo: {id: 1, ...cacheInfo.scfInfoDto},
                    }
                    break;
                case "CAT":
                    params = {
                        catDetailDtos: cacheInfo.scfDetailDtos,
                        catInfo: {id: 1, ...cacheInfo.scfInfoDto},
                    }
                    break;
                case "2nd Payment":
                    params = {
                        downPaymentDto2: {...cacheInfo.downPaymentDto, id: 1},
                        downPaymentDetailDtos: cacheInfo.downPaymentDetailDtos,
                        dpSubmitProgressCode: cacheInfo.dpSubmitProgressCode
                    }
                    break;
                case "FAT":
                    params = {
                        fatDetailDtos: cacheInfo.scfDetailDtos,
                        fatInfo: {id: 1, ...cacheInfo.scfInfoDto},
                    }
                    break;
                case "3nd Payment":
                    params = {
                        downPaymentDto3: {...cacheInfo.downPaymentDto, id: 1},
                        downPaymentDetailDtos: cacheInfo.downPaymentDetailDtos,
                        dpSubmitProgressCode: cacheInfo.dpSubmitProgressCode
                    }
                    break;
                case "Capitalization":
                    params = {
                        capexCapitalizationInfoDTO: {
                            ...cacheInfo.capexCapitalizationInfoDTO,
                            acquisitionMethodCCD: cacheInfo.capexCapitalizationInfoDTO.acquisitionMethod,
                            id: 1
                        },
                        capexCapitalizationDetails: cacheInfo.capexCapitalizationDetails,
                        assetNos: cacheInfo.assetNos
                    }
                    break;
                case "Post Calculation":
                    params = {
                        ...cacheInfo
                    }
                    break;
            }


            delete params.progressCode
            delete params.id

            return {
                flows,
                ...params
            }
        },
        detectionFieldMethod(list1, list2, fields) {

            if (!(Array.isArray(fields) && fields.length > 0)) {
                return false;
            }
            if (!(Array.isArray(list1) && list1.length > 0)) {
                return false;
            }

            if (!(Array.isArray(list2) && list2.length > 0)) {
                return false;
            }

            list1 = list1.filter(item => {
                if (item.operation != 'action') return item;
            })

            list2 = list2.filter(item => {
                if (item.operation != 'action') return item;
            })
            if (list2.length !== list1.length) {
                return false;
            }


            let status = true
            label: for (let i = 0; i < list1.length; i++) {
                for (let k = 0; k < fields.length; k++) {
                    if (list1[i][fields[k]] != list2[i][fields[k]]) {
                        status = false;
                        break label;
                    }
                }
            }



            return status
        }
    }
}
